<template>
  <div class="a2-container">
    <div class="header">
      <h1><el-icon><Document /></el-icon> A2用户界面</h1>
      <div class="user-info">
        <span class="welcome"><el-icon><User /></el-icon> 欢迎，</span>
        <span class="username">{{ username }}</span>
        <button class="logout-btn" @click="handleLogout">
          <el-icon><SwitchButton /></el-icon> 退出登录
        </button>
      </div>
    </div>
    
    <div class="processed-count-text">
      <el-icon><DataLine /></el-icon> 已处理文档数：{{ processedCount }}
    </div>
    
    <div class="main-content">
      <!-- 文献下载部分 -->
      <div class="section literature-section">
        <h2><el-icon><Files /></el-icon> 文献列表</h2>
        <div class="literature-list" v-if="literatureList.length > 0">
          <div v-for="item in literatureList" 
               :key="item.id" 
               :class="['literature-item', { active: selectedPdfId === item.id }]">
            <div class="literature-info">
              <el-radio 
                v-model="selectedPdfId" 
                :label="item.id"
                @change="handlePdfSelect">
                <el-icon><Document /></el-icon> {{ item.name }}
              </el-radio>
              <span class="literature-time"><el-icon><Timer /></el-icon> 上传时间：{{ item.uploadTime }}</span>
            </div>
            <button class="download-btn" @click="downloadLiterature(item)">
              <el-icon><Download /></el-icon> 下载文献
            </button>
          </div>
        </div>
        <div v-else class="no-data">
          <el-icon><Warning /></el-icon> 暂无可选择的PDF文件
        </div>
      </div>

      <!-- 问答对提交部分 -->
      <div class="section qa-section">
        <div class="section-header">
          <h2><el-icon><ChatDotRound /></el-icon> 问答对提交</h2>
          <div class="header-actions">
            <el-button 
              type="primary" 
              link
              @click="downloadTemplate"
              class="download-template-btn">
              <el-icon><Download /></el-icon>
              下载模板
            </el-button>
            <el-upload
              class="upload-json"
              action="#"
              :auto-upload="false"
              :show-file-list="false"
              accept=".json"
              @change="handleJsonFileChange">
              <el-button type="primary">
                <el-icon><Upload /></el-icon>
                上传JSON文件
              </el-button>
            </el-upload>
          </div>
        </div>
        <div class="qa-list">
          <div v-if="qaList.length > 0">
            <!-- 当前页的问答对 -->
            <div class="qa-item">
              <div class="qa-header">
                <span class="qa-index"><el-icon><List /></el-icon> 问答对 #{{ currentPage }}/{{ totalPages }}</span>
                <button class="delete-btn" 
                        @click="removeCurrentQa"
                        :disabled="qaList.length <= 1">
                  <el-icon><Delete /></el-icon> 删除
                </button>
              </div>
              <div class="qa-content">
                <div class="input-group">
                  <label><el-icon><QuestionFilled /></el-icon> 问题：</label>
                  <textarea 
                    v-model="currentQa.instruction"
                    placeholder="请输入问题"
                    rows="3"
                  ></textarea>
                </div>
                <div class="input-group">
                  <label><el-icon><ChatLineRound /></el-icon> 答案：</label>
                  <textarea 
                    v-model="currentQa.output"
                    placeholder="请输入答案"
                    rows="5"
                  ></textarea>
                </div>
              </div>
            </div>

            <!-- 分页控制 -->
            <div class="pagination-container">
              <div class="page-buttons">
                <button 
                  class="page-btn" 
                  @click="previousPage"
                  :disabled="currentPage <= 1">
                  <el-icon><ArrowLeft /></el-icon> 上一页
                </button>
                <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
                <button 
                  class="page-btn" 
                  @click="nextPage"
                  :disabled="currentPage >= totalPages">
                  下一页 <el-icon><ArrowRight /></el-icon>
                </button>
              </div>
            </div>
          </div>
          <div v-else class="no-data">
            <div class="upload-area"
                 @dragover.prevent
                 @drop.prevent="handleDrop"
                 @dragenter.prevent="handleDragEnter"
                 @dragleave.prevent="handleDragLeave"
                 :class="{ 'drag-over': isDragging }">
              <el-icon class="upload-icon"><Upload /></el-icon>
              <p>请上传JSON文件或下载模板</p>
              <p class="upload-tip">也可以将文件拖拽到此处</p>
            </div>
          </div>

          <div class="qa-actions">
            <button 
              class="submit-btn" 
              @click="submitQaPairs"
              :disabled="!canSubmit">
              <el-icon><Check /></el-icon> 提交全部
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { useRouter } from 'vue-router';
import request from '@/utils/request';
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { 
  Download, 
  Upload, 
  Document,
  User,
  SwitchButton,
  DataLine,
  Files,
  Timer,
  Warning,
  ChatDotRound,
  List,
  Delete,
  QuestionFilled,
  ChatLineRound,
  ArrowLeft,
  ArrowRight,
  Check
} from '@element-plus/icons-vue';

export default {
  name: 'A2Main',
  components: {
    Download,
    Upload,
    Document,
    User,
    SwitchButton,
    DataLine,
    Files,
    Timer,
    Warning,
    ChatDotRound,
    List,
    Delete,
    QuestionFilled,
    ChatLineRound,
    ArrowLeft,
    ArrowRight,
    Check
  },
  setup() {
    const router = useRouter();
    const username = ref('');
    const literatureList = ref([]);
    const qaList = ref([]);
    const loading = ref(false);
    const currentPage = ref(1);
    const selectedPdfId = ref(null);
    const processedCount = ref(0);
    const jsonFile = ref(null);
    const isDragging = ref(false);

    // 计算总页数
    const totalPages = computed(() => qaList.value.length);

    // 当前问答对
    const currentQa = computed({
      get: () => qaList.value[currentPage.value - 1] || {
        instruction: '',
        input: '',
        output: '',
        system: ''
      },
      set: (value) => {
        if (currentPage.value <= qaList.value.length) {
          qaList.value[currentPage.value - 1] = value;
        }
      }
    });

    // 是否可以提交
    const canSubmit = computed(() => 
      qaList.value.length > 0 && 
      qaList.value.every(qa => qa.instruction.trim() && qa.output.trim())
    );

    // 初始化问答对列表
    const initQaList = () => {
      qaList.value = [];
      currentPage.value = 1;
    };

    // 删除当前问答对
    const removeCurrentQa = () => {
      if (qaList.value.length <= 1) return;
      
      qaList.value.splice(currentPage.value - 1, 1);
      if (currentPage.value > qaList.value.length) {
        currentPage.value = qaList.value.length;
      }
    };

    // 上一页
    const previousPage = () => {
      if (currentPage.value > 1) {
        currentPage.value--;
      }
    };

    // 下一页
    const nextPage = () => {
      if (currentPage.value < totalPages.value) {
        currentPage.value++;
      }
    };

    // 处理JSON文件上传
    const handleJsonFileChange = (file) => {
      if (!file) return;
      
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const content = JSON.parse(e.target.result);
          if (Array.isArray(content)) {
            qaList.value = content;
            currentPage.value = 1;
            jsonFile.value = file.raw;
            ElMessage.success('JSON文件解析成功');
          } else {
            throw new Error('JSON格式不正确，应为数组格式');
          }
        } catch (error) {
          console.error('JSON解析失败:', error);
          ElMessage.error('JSON文件格式不正确，请检查文件内容');
        }
      };
      reader.readAsText(file.raw);
    };

    // 提交问答对
    const submitQaPairs = async () => {
      if (!canSubmit.value) return;
      if (!selectedPdfId.value) {
        ElMessage.warning('请选择一个PDF文件');
        return;
      }
      if (!jsonFile.value) {
        ElMessage.warning('请先上传JSON文件');
        return;
      }

      try {
        loading.value = true;
        
        // 准备提交的数据
        const submitData = {
          id: selectedPdfId.value,
          list: qaList.value.map(qa => ({
            instruction: qa.instruction || '',
            input: qa.input || '',
            output: qa.output || '',
            system: qa.system || ''
          })),
          count: qaList.value.length
        };
        
        console.log('提交的数据：', submitData);
        
        // 调用后端API
        const response = await request({
          url: 'http://10.137.10.169:8080/api/me/qa',
          method: 'post',
          data: submitData
        });
        
        if (response.data.code === 200) {
          ElMessage.success('提交成功');
          
          // 重置表单
          qaList.value = [];
          selectedPdfId.value = null;
          jsonFile.value = null;
          initQaList();
          
          // 刷新文献列表和已处理文档数量
          await Promise.all([
            fetchLiteratureList(),
            fetchProcessedCount()
          ]);
        } else {
          throw new Error(response.data.msg || '提交失败');
        }
      } catch (error) {
        console.error('提交问答对失败:', error);
        ElMessage.error(error.message || '提交失败，请重试');
      } finally {
        loading.value = false;
      }
    };

    // 获取文献列表
    const fetchLiteratureList = async () => {
      try {
        loading.value = true;
        
        // 获取文件列表
        const response = await request.get('http://localhost:8080/api/me/file/qa');
        console.log("文件列表数据：", response.data);
        
        if (response.data.code === 200) {
          // 获取每个文件的详细信息
          const fileDetails = await Promise.all(
            response.data.data.map(async (file) => {
              try {
                const detailResponse = await request.get(`http://localhost:8080/api/file/info/${file.fileId}`);
                if (detailResponse.data.code === 200) {
                  return {
                    id: file.id,
                    name: detailResponse.data.data.fileName,
                    uploadTime: detailResponse.data.data.uploadTime,
                    status: file.status,
                    major: file.major,
                    contentSummary: file.contentSummary,
                    articleTitle: file.articleTitle,
                    downloading: false
                  };
                }
                return null;
              } catch (error) {
                console.error(`获取文件${file.fileId}详情失败:`, error);
                return null;
              }
            })
          );
          
          // 过滤掉获取失败的文件
          literatureList.value = fileDetails.filter(file => file !== null);
        } else {
          throw new Error(response.data.msg || '获取文献列表失败');
        }
      } catch (error) {
        console.error('获取文献列表失败:', error);
        ElMessage.error('获取文献列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 下载文献
    const downloadLiterature = async (item) => {
      if (!item.downloading) {
        item.downloading = true;
        try {
          const response = await request({
            url: `http://10.137.10.169:8080/api/file/download/${item.id}`,
            method: 'GET',
            responseType: 'blob'
          });
          
          // 创建下载链接
          const blob = new Blob([response.data], { type: 'application/pdf' });
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = item.name;
          
          // 触发下载
          document.body.appendChild(link);
          link.click();
          
          // 清理
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);

          ElMessage.success('下载成功');
        } catch (error) {
          console.error('文献下载失败:', error);
          ElMessage.error('下载失败，请重试');
        } finally {
          item.downloading = false;
        }
      }
    };

    // 处理PDF选择
    const handlePdfSelect = () => {
      console.log('已选择的PDF:', selectedPdfId.value);
    };

    // 退出登录
    const handleLogout = () => {
      localStorage.removeItem('isLoggedIn');
      localStorage.removeItem('username');
      localStorage.removeItem('userRole');
      localStorage.removeItem('token');
      router.push('/login');
    };

    // 下载问答对模板
    const downloadTemplate = () => {
      // 模板数据
      const templateData = [
        {
          "instruction": "这是问题示例1",
          "output": "这是答案示例1",
          "input": "",
          "system": ""
        },
        {
          "instruction": "这是问题示例2",
          "output": "这是答案示例2",
          "input": "",
          "system": ""
        }
      ];

      // 将数据转换为JSON字符串
      const jsonStr = JSON.stringify(templateData, null, 2);
      
      // 创建Blob对象
      const blob = new Blob([jsonStr], { type: 'application/json' });
      
      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = 'qa_template.json';
      
      // 触发下载
      document.body.appendChild(link);
      link.click();
      
      // 清理
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      ElMessage.success('模板下载成功');
    };

    // 获取处理文档数量
    const fetchProcessedCount = async () => {
      try {
        const response = await request({
          method: 'get',
          url: 'http://localhost:8080/api/Static'
        });
        
        if (response.data && response.data.code === 200) {
          processedCount.value = response.data.qaCount.all;
        } else {
          throw new Error(response.data?.msg || '获取数据失败');
        }
      } catch (error) {
        console.error('获取处理文档数量失败:', error);
        ElMessage.error('获取处理文档数量失败');
      }
    };

    // 处理拖拽进入
    const handleDragEnter = () => {
      isDragging.value = true;
    };

    // 处理拖拽离开
    const handleDragLeave = () => {
      isDragging.value = false;
    };

    // 处理文件拖放
    const handleDrop = (e) => {
      isDragging.value = false;
      const files = e.dataTransfer.files;
      if (files.length > 0) {
        const file = files[0];
        if (file.type === 'application/json' || file.name.endsWith('.json')) {
          handleJsonFileChange({ raw: file });
        } else {
          ElMessage.error('请上传JSON格式的文件');
        }
      }
    };

    // 初始化
    username.value = localStorage.getItem('username') || '用户';
    fetchLiteratureList();
    initQaList();
    fetchProcessedCount();

    return {
      username,
      literatureList,
      qaList,
      loading,
      currentPage,
      totalPages,
      currentQa,
      canSubmit,
      removeCurrentQa,
      previousPage,
      nextPage,
      downloadLiterature,
      submitQaPairs,
      handleLogout,
      selectedPdfId,
      handlePdfSelect,
      downloadTemplate,
      processedCount,
      handleJsonFileChange,
      isDragging,
      handleDragEnter,
      handleDragLeave,
      handleDrop,
    };
  }
};
</script>

<style scoped>
.a2-container {
  width: 100%;
  min-width: 1200px;
  padding: 20px;
  box-sizing: border-box;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.header h1 {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #303133;
  margin: 0;
  font-size: 24px;
}

.header h1 .el-icon {
  font-size: 28px;
  color: #409EFF;
}

.main-content {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.section {
  flex: 1;
  background-color: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.section:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
}

.section h2 {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #303133;
  margin: 0 0 20px 0;
  font-size: 20px;
}

.section h2 .el-icon {
  color: #409EFF;
}

/* 文献下载部分样式 */
.literature-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #eaeaea;
  border-radius: 8px;
  margin-bottom: 12px;
  transition: all 0.3s ease;
  background-color: #fff;
}

.literature-item.active {
  border-color: #409EFF;
  background-color: #ecf5ff;
  transform: translateY(-2px);
}

.literature-item:hover {
  background-color: #f5f7fa;
  transform: translateY(-2px);
}

.literature-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex: 1;
}

.literature-time {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
  color: #909399;
}

.download-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 8px 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.download-btn:hover {
  background-color: #66b1ff;
  transform: translateY(-1px);
}

/* 问答对部分样式 */
.qa-item {
  border: 1px solid #eaeaea;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.qa-item:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
}

.qa-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #eaeaea;
}

.qa-index {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: bold;
  color: #409EFF;
}

.delete-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  background-color: #F56C6C;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 6px 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.delete-btn:hover {
  background-color: #f78989;
  transform: translateY(-1px);
}

.delete-btn:disabled {
  background-color: #fab6b6;
  cursor: not-allowed;
  transform: none;
}

.input-group {
  margin-bottom: 20px;
}

.input-group label {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 10px;
  color: #606266;
  font-weight: 500;
}

textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  resize: vertical;
  font-size: 14px;
  transition: all 0.3s ease;
  background-color: #fafafa;
}

textarea:focus {
  outline: none;
  border-color: #409EFF;
  background-color: #fff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.qa-actions {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

.submit-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 10px 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 15px;
}

.submit-btn:hover {
  background-color: #66b1ff;
  transform: translateY(-1px);
}

.submit-btn:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
  transform: none;
}

.no-data {
  text-align: center;
  color: #909399;
  padding: 32px;
  background-color: #fafafa;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.no-data .el-icon {
  font-size: 48px;
  color: #909399;
}

/* 用户信息样式 */
.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.welcome {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 15px;
  color: #606266;
}

.username {
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
}

.logout-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  background-color: #f56c6c;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 8px 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.logout-btn:hover {
  background-color: #e64242;
  transform: translateY(-1px);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.processed-count-text {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 15px;
  color: #606266;
  margin: 20px 0;
  padding: 12px 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin: 24px 0;
}

.page-buttons {
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 8px 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.page-btn:hover {
  background-color: #66b1ff;
  transform: translateY(-1px);
}

.page-btn:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
  transform: none;
}

.page-info {
  font-size: 14px;
  color: #606266;
  margin: 0 12px;
}

.upload-area {
  border: 2px dashed #dcdfe6;
  border-radius: 12px;
  padding: 48px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #fafafa;
}

.upload-area:hover {
  border-color: #409EFF;
  background-color: #f5f7fa;
  transform: translateY(-2px);
}

.upload-area.drag-over {
  border-color: #409EFF;
  background-color: #ecf5ff;
  transform: translateY(-2px);
}

.upload-icon {
  font-size: 48px;
  color: #909399;
  margin-bottom: 16px;
}

.upload-tip {
  font-size: 13px;
  color: #909399;
  margin-top: 8px;
}

/* 响应式调整 */
@media screen and (max-width: 1200px) {
  .main-content {
    flex-direction: column;
  }
  
  .section {
    width: 100%;
  }
}
</style> 